﻿using System;

namespace DotNetImage.Imaging.Filters
{
    /// <summary>
    /// This one works by working out the greatest difference between a pixel and it's eight neighbours.
    /// The threshold allows softer edges to be forced down to black, use 0 to negate it's effect.
    /// Max value assigned to central pixel. And calculated as (per color):
    /// d1 = ABS(m11 - m13)
    /// d2 = ABS(m31 - m33)
    /// d3 = ABS(m12 - m32)
    /// d4 = ABS(m21 - m23)
    /// m22 = MAX(d1, d2, d3, d4)
    /// </summary>
    public class EdgeDetectDifferenceFilter : Conv3x3
    {
        [ParameterAttribute(Name = "Treshold", DefaultValue = 0, MinValue = 0, MaxValue = 255, Step = 1)]
        public byte Treshold { get; set; }

        [ParameterAttribute(Name = "Edge Detection Type", DefaultValue = (int)EdgeDetectionType.EDGE_DETECT_DIFFERENCE)]
        public EdgeDetectionType DetectionType { get { return EdgeDetectionType.EDGE_DETECT_DIFFERENCE; } }

        protected override void PrepareData(DotNetImage bmp)
        {
            base.PrepareData(bmp);
            bmp.CreatePixelCopy();
            startX = 1;
            startY = 1;
        }

        protected override void ProcessPixel(ref Pixel pix, uint x = 0, uint y = 0)
        {
            Pixel pix11 = Subject.GetPreservedPixel(x - 1, y - 1);
            Pixel pix12 = Subject.GetPreservedPixel(x, y - 1);
            Pixel pix13 = Subject.GetPreservedPixel(x + 1, y - 1);
            Pixel pix21 = Subject.GetPreservedPixel(x - 1, y);
            Pixel pix23 = Subject.GetPreservedPixel(x + 1, y);
            Pixel pix31 = Subject.GetPreservedPixel(x - 1, y + 1);
            Pixel pix32 = Subject.GetPreservedPixel(x, y + 1);
            Pixel pix33 = Subject.GetPreservedPixel(x + 1, y + 1);

            pix11.SubtractAbs(pix13);
            pix31.SubtractAbs(pix33);
            pix12.SubtractAbs(pix32);
            pix21.SubtractAbs(pix23);

            pix = Pixel.GetMax(Treshold, pix11, pix31, pix12, pix21);
        }
    }
}
